import {
  DownloadOutlined,
  CloseOutlined,
  SaveOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Button, Space, Image, message, Divider, Tooltip, Modal } from "antd";
import dayjs from "dayjs";
import html2canvas from "html2canvas";
import { cloneDeep, forEach, includes, isEqual } from "lodash";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";

import U3204 from "../../../assets/imgs/u3204.png";
import U3208 from "../../../assets/imgs/u3208.png";
import { ChartItem } from "../models";

import { useAnalysisTask } from "~/components/Visualization/store/useTaskState";
import {
  createTaskDocument,
  updateTaskDocument,
} from "~/hooks/Visualization/use-visualization-api";
import { Mutation } from "~/modules/api-server/types";
import {
  MutationUpdateTaskArgs,
  MutationCreateTaskArgs,
} from "~/modules/api-server/types2";
import { formatDate, formatDateTZ } from "~/modules/shared/utils/common";
import { RawWorkSpaceState } from "~/modules/worker/schedule";
import { useWorkSpace } from "~/modules/workspace/store/use-workspace";
import { getContent } from "~/plugins/api-server";
import "./workspace-header.scss";
export interface WorkSpaceHeaderProps {
  splitType: string;
  MergeSplit: Function;
  Open: Function;
}

const WorkSpaceHeader = (props: WorkSpaceHeaderProps) => {
  const [messageApi, contextHolder] = message.useMessage();
  const { workSpace, flights } = useWorkSpace();
  const { analysisTask } = useAnalysisTask();
  const [isIcon, setIcon] = useState(true);
  const router = useNavigate();
  const [isSplit, setSplit] = useState(props.splitType);
  // 创建任务
  const [CreateTask, { data: createData }] = useMutation<
    Mutation,
    MutationCreateTaskArgs
  >(createTaskDocument, {
    client: getContent().explorer_apiServer,
  });
  useEffect(() => {
    if (createData) {
      messageApi.success("新建成功");
      router("/");
    }
  }, [createData]);
  // 更新任务
  const [UpdateTask1, { data: updateData }] = useMutation<
    Mutation,
    MutationUpdateTaskArgs
  >(updateTaskDocument, {
    client: getContent().explorer_apiServer,
  });
  useEffect(() => {
    if (updateData) {
      messageApi.success("编辑成功");
      router("/");
    }
  }, [updateData]);

  // 合并
  const ChartList: ChartItem[] = [];
  const onMerge = () => {
    props.MergeSplit(true);
    setSplit("merge");
  };
  // 下载
  const onDownload = () => {
    const download = () => {
      html2canvas(document.getElementById("ChartList") as HTMLElement).then(
        function (canvas: { toDataURL: (arg0: string) => string }) {
          const img = canvas
            .toDataURL("image/png")
            .replace("image/png", "image/octet-stream"); // 创建a标签，实现下载
          const creatIMg = document.createElement("a");
          creatIMg.download = `${analysisTask.name}.png`; // 设置下载的文件名，
          creatIMg.href = img; // 下载url
          document.body.appendChild(creatIMg);
          creatIMg.click();
          creatIMg.remove(); // 下载之后把创建的元素删除
        }
      );
    };

    download();
  };
  // 拆分
  const onSplit = () => {
    props.MergeSplit(false);
    setSplit("disassemble");
  };
  // 取消
  const onCancel = () => {
    if (
      !isEqual(RawWorkSpaceState.workSpace, workSpace) ||
      !isEqual(RawWorkSpaceState.flights, analysisTask.flights) ||
      !isEqual(RawWorkSpaceState.startTime, analysisTask.startTime) ||
      !isEqual(RawWorkSpaceState.endTime, analysisTask.endTime)
    ) {
      showConfirm("未点击保存，确认离开吗？系统不会保存你的更改！");
    } else {
      router("/");
    }
  };

  const showConfirm = (title: string, content?: string) => {
    Modal.confirm({
      title,
      icon: <ExclamationCircleOutlined />,
      content,
      onOk() {
        router("/");
      },
      onCancel() {},
    });
  };

  // 保存
  const onSave = () => {
    forEach(workSpace.splitCharts, (item) => {
      forEach(item.data, (m) => {
        if (m.isOpen) {
          delete m.isOpen;
        }
      });
    });

    const data: any = {
      id: analysisTask.id,
      start_time: !includes(analysisTask.startTime, "T")
        ? formatDateTZ(analysisTask.startTime)
        : analysisTask.startTime,
      end_time: !includes(analysisTask.startTime, "T")
        ? formatDateTZ(analysisTask.endTime)
        : analysisTask.endTime,
      flights: analysisTask.flights,
      workspace: workSpace,
    };

    if (analysisTask.type === "edit") {
      data.id = analysisTask.id;

      UpdateTask1({
        variables: {
          input: data,
        },
      });
    } else {
      data.uid = "";
      data.name = analysisTask.name;
      data.tailNo = analysisTask.tailno;
      data.aircraftId = analysisTask.aircraftId;
      forEach(data.calculatedParameter, (item) => {
        Reflect.deleteProperty(item, "id");
      });
      CreateTask({
        variables: {
          input: data,
        },
      });
    }

    //保存原始的数据
    RawWorkSpaceState.flights = cloneDeep(flights);
    RawWorkSpaceState.workSpace = cloneDeep(workSpace);
    // router("/");
  };
  // 参数列表 收起/展开
  const onIsStow = (state: boolean) => {
    props.Open(state);
    setIcon(state);
  };

  return (
    <div className="flex pt-5px pr-16px pb-5px pl-16px border-b-1px border-#EAEEF7">
      <div className="flex-1 flex justify-start top-content">
        {isIcon ? (
          <Button
            type="text"
            icon={
              <MenuFoldOutlined
                style={{ fontSize: "20px" }}
                onClick={() => onIsStow(false)}
              />
            }
          />
        ) : (
          <Button
            type="text"
            icon={
              <MenuUnfoldOutlined
                style={{ fontSize: "20px" }}
                onClick={() => onIsStow(true)}
              />
            }
          />
        )}
        <Tooltip title={analysisTask.name}>
          <p
            className="max-w-300px text-16px color-#2B2325 mb-0 pl-16px pr-16px truncate"
            style={{ lineHeight: "32px" }}
          >
            {analysisTask.name}
          </p>
        </Tooltip>

        <Divider className="h-32px!" type="vertical" />
        {isSplit === "disassemble" ? (
          <Button
            type="text"
            icon={
              <Image
                width={20}
                height={15}
                preview={false}
                src={U3204}
                style={{ paddingRight: "6px" }}
              />
            }
            onClick={() => onMerge()}
          >
            合并
          </Button>
        ) : (
          <Button
            type="text"
            icon={
              <Image
                width={20}
                preview={false}
                src={U3208}
                style={{ paddingRight: "6px" }}
              />
            }
            onClick={() => onSplit()}
          >
            拆分
          </Button>
        )}
        <Button
          icon={
            <DownloadOutlined style={{ fontSize: "18px", color: "#5E7CE0" }} />
          }
          type="text"
          onClick={() => onDownload()}
        >
          下载
        </Button>
      </div>
      <div className="flex-1 flex justify-center sub-content">
        <p
          className="text-12px flex flex-nowrap color-#6C7280 m-0"
          style={{ lineHeight: "32px" }}
        >
          <span>机尾号：</span>
          <span>{analysisTask.tailno}</span>
        </p>
        <p
          className="text-12px flex flex-nowrap color-#6C7280 mb-0 ml-20px"
          style={{ lineHeight: "32px" }}
        >
          <span>时间段：</span>
          <span>
            {formatDate(analysisTask.startTime) +
              " ~ " +
              formatDate(analysisTask.endTime)}
          </span>
        </p>
      </div>
      <div className="flex-1 flex justify-end">
        <Button icon={<CloseOutlined />} type="link" onClick={() => onCancel()}>
          退出
        </Button>
        <Button icon={<SaveOutlined />} type="link" onClick={() => onSave()}>
          保存
        </Button>
      </div>
      {contextHolder}
    </div>
  );
};

export default WorkSpaceHeader;
const headerStyle = {
  //   height: '48px',
  display: "flex",
  justifyContent: "space-between",
  padding: "5px 16px",
  borderBottom: "1px solid #EAEEF7",
};
